<?php
/**
 * 写入静态页面缓存
 */
function write_html_cache($html){
    $html_cache_arr = C('HTML_CACHE_ARR');
    $request = think\Request::instance();
    $m_c_a_str = $request->module().'_'.$request->controller().'_'.$request->action(); // 模块_控制器_方法
    $m_c_a_str = strtolower($m_c_a_str);
    //exit('write_html_cache写入缓存<br/>');
    foreach($html_cache_arr as $key=>$val)
    {
        $val['mca'] = strtolower($val['mca']);
        if($val['mca'] != $m_c_a_str) //不是当前 模块 控制器 方法 直接跳过
            continue;

        //if(!is_dir(RUNTIME_PATH.'html'))
        //mkdir(RUNTIME_PATH.'html');
        //$filename =  RUNTIME_PATH.'html'.DIRECTORY_SEPARATOR.$m_c_a_str;
        $filename =  $m_c_a_str;
        // 组合参数
        if(isset($val['p']))
        {
            foreach($val['p'] as $k=>$v)
                $filename.='_'.$_GET[$v];
        }
        $filename.= '.html';
        \think\Cache::set($filename,$html);
        //file_put_contents($filename, $html);
    }
}

// 应用公共文件
if (!function_exists('pr')) {
    function pr($var,$exit='') {
        if (true) {
            $template = PHP_SAPI !== 'cli' ? '<pre>%s</pre>' : "\n%s\n";
            printf($template, print_r($var, true));
            if(!empty($exit))   exit($exit);
        }
    }
}
/**
* 读取静态页面缓存
*/
function read_html_cache(){
    $html_cache_arr = C('HTML_CACHE_ARR');
    $request = think\Request::instance();
    $m_c_a_str = $request->module().'_'.$request->controller().'_'.$request->action(); // 模块_控制器_方法
    $m_c_a_str = strtolower($m_c_a_str);
    //exit('read_html_cache读取缓存<br/>');
    foreach($html_cache_arr as $key=>$val){
        $val['mca'] = strtolower($val['mca']);
        if($val['mca'] != $m_c_a_str) //不是当前 模块 控制器 方法 直接跳过
        continue;

        //$filename =  RUNTIME_PATH.'html'.DIRECTORY_SEPARATOR.$m_c_a_str;
        $filename =  $m_c_a_str;
        // 组合参数
        if(isset($val['p'])){
            foreach($val['p'] as $k=>$v)
            $filename.='_'.$_GET[$v];
        }
        $filename.= '.html';
        $html = \think\Cache::get($filename);
        if($html){
            //echo file_get_contents($filename);
            echo \think\Cache::get($filename);
            exit();
        }
    }
}
/**
 * 获取缓存或者更新缓存
 * @param string $config_key 缓存文件名称
 * @param array $data 缓存数据  array('k1'=>'v1','k2'=>'v3')
 * @return array or string or bool
 */
function tpCache($config_key,$data = array()){
    $param = explode('.', $config_key);
    if(empty($data)){
        $config = F($param[0],'',TEMP_PATH);//直接获取缓存文件
        if(empty($config)){
            //缓存文件不存在就读取数据库
            $res = D('config')->where("inc_type",$param[0])->select();
            if($res){
                foreach($res as $k=>$val){
                    $config[$val['name']] = $val['value'];
                }
                F($param[0],$config,TEMP_PATH);
            }
        }
        if(count($param)>1){
            return $config[$param[1]];
        }else{
            return $config;
        }
    }else{
        //更新缓存
        $result =  D('config')->where("inc_type", $param[0])->select();
        if($result){
            foreach($result as $val){
                $temp[$val['name']] = $val['value'];
            }
            foreach ($data as $k=>$v){
                $newArr = array('name'=>$k,'value'=>trim($v),'inc_type'=>$param[0]);
                if(!isset($temp[$k])){
                    M('config')->add($newArr);//新key数据插入数据库
                }else{
                    if($v!=$temp[$k])
                        M('config')->where("name", $k)->save($newArr);//缓存key存在且值有变更新此项
                }
            }
            //更新后的数据库记录
            $newRes = D('config')->where("inc_type", $param[0])->select();
            foreach ($newRes as $rs){
                $newData[$rs['name']] = $rs['value'];
            }
        }else{
            foreach($data as $k=>$v){
                $newArr[] = array('name'=>$k,'value'=>trim($v),'inc_type'=>$param[0]);
            }
            M('config')->insertAll($newArr);
            $newData = $data;
        }
        return F($param[0],$newData,TEMP_PATH);
    }
}
/**
* 验证验
* @param string $id 验证码身份 如：'think'
* @return object 图片
 */
function verify($id=''){
    ob_end_clean();
    $config = array(
        'fontSize' => 30,
        'length' => 4,
        'useCurve' => true,
        'useNoise' => false,
        'reset' => false,
        'fontttf' => '4.ttf'
    );
    $Verify = new think\Verify($config);
    $Verify->entry($id);
    exit();
}
/**
 * 验证验证码
 * @param string $code 验证码
 * @param string $id 验证码身份 如：'think'
 * @return bool
 */
function check($code,$id=''){
    $Verify = new think\Verify();
    return $Verify->check($code,$id);
}

//默认头像
function head_img($img,$a = false){
    if(empty($img)){
        $host = '';
        if($a){
            $host = SITE_URL;
        }
        $img = $host.'/public/images/tb2_03.png';
    }
    return $img;
}

//默认商品图片
function goods_img($img){
    if(empty($img)){
        $img = '/public/home/images/goods_img.jpg';
    }
    return $img;
}
/**
 * 刷新商品库存, 如果商品有设置规格库存, 则商品总库存 等于 所有规格库存相加
 * @param type $goods_id  商品id
 */
function refresh_stock($goods_id){
    $count = M("spec_goods_price")->where("goods_id", $goods_id)->count();
    if($count == 0) return false; // 没有使用规格方式 没必要更改总库存

    $store_count = M("spec_goods_price")->where("goods_id", $goods_id)->sum('store_count');
    // 更新商品的总库存
    M("goods")->where("goods_id", $goods_id)->save(array('store_count' => $store_count));
}
/**
 *  商品缩略图 给于标签调用 拿出商品表的 original_img 原始图来裁切出来的
 * @param type $goods_id  商品id
 * @param type $width     生成缩略图的宽度
 * @param type $height    生成缩略图的高度
 */
function goods_thum_images($goods_id, $width, $height){
    if (empty($goods_id)) return '';

    //判断缩略图是否存在
    $path = "public/upload/goods/thumb/$goods_id/";
    $goods_thumb_name = "goods_thumb_{$goods_id}_{$width}_{$height}";

    // 这个商品 已经生成过这个比例的图片就直接返回了
    if (is_file($path . $goods_thumb_name . '.jpg')) return '/' . $path . $goods_thumb_name . '.jpg';
    if (is_file($path . $goods_thumb_name . '.jpeg')) return '/' . $path . $goods_thumb_name . '.jpeg';
    if (is_file($path . $goods_thumb_name . '.gif')) return '/' . $path . $goods_thumb_name . '.gif';
    if (is_file($path . $goods_thumb_name . '.png')) return '/' . $path . $goods_thumb_name . '.png';

    $original_img = M('Goods')->cache(true, 3600)->where("goods_id", $goods_id)->getField('original_img');
    if (empty($original_img)) {
        return '/public/images/icon_goods_thumb_empty_300.png';
    }

    $ossClient = new \app\common\logic\OssLogic;
    if (($ossUrl = $ossClient->getGoodsThumbImageUrl($original_img, $width, $height))) {
        return $ossUrl;
    }

    $original_img = '.' . $original_img; // 相对路径
    if (!is_file($original_img)) {
        return '';
    }

    try {
        vendor('topthink.think-image.src.Image');
        if(strstr(strtolower($original_img),'.gif'))
        {
            vendor('topthink.think-image.src.image.gif.Encoder');
            vendor('topthink.think-image.src.image.gif.Decoder');
            vendor('topthink.think-image.src.image.gif.Gif');
        }
        $image = \think\Image::open($original_img);

        $goods_thumb_name = $goods_thumb_name . '.' . $image->type();
        // 生成缩略图
        !is_dir($path) && mkdir($path, 0777, true);
        // 参考文章 http://www.mb5u.com/biancheng/php/php_84533.html  改动参考 http://www.thinkphp.cn/topic/13542.html
        $image->thumb($width, $height, 2)->save($path . $goods_thumb_name, NULL, 100); //按照原图的比例生成一个最大为$width*$height的缩略图并保存
        //图片水印处理
        $water = tpCache('water');
        if ($water['is_mark'] == 1) {
            $imgresource = './' . $path . $goods_thumb_name;
            if ($width > $water['mark_width'] && $height > $water['mark_height']) {
                if ($water['mark_type'] == 'img') {
                    //检查水印图片是否存在
                    $waterPath = "." . $water['mark_img'];
                    if (is_file($waterPath)) {
                        $quality = $water['mark_quality'] ?: 80;
                        $waterTempPath = dirname($waterPath).'/temp_'.basename($waterPath);
                        $image->open($waterPath)->save($waterTempPath, null, $quality);
                        $image->open($imgresource)->water($waterTempPath, $water['sel'], $water['mark_degree'])->save($imgresource);
                        @unlink($waterTempPath);
                    }
                } else {
                    //检查字体文件是否存在,注意是否有字体文件
                    $ttf = './hgzb.ttf';
                    if (file_exists($ttf)) {
                        $size = $water['mark_txt_size'] ?: 30;
                        $color = $water['mark_txt_color'] ?: '#000000';
                        if (!preg_match('/^#[0-9a-fA-F]{6}$/', $color)) {
                            $color = '#000000';
                        }
                        $transparency = intval((100 - $water['mark_degree']) * (127/100));
                        $color .= dechex($transparency);
                        $image->open($imgresource)->text($water['mark_txt'], $ttf, $size, $color, $water['sel'])->save($imgresource);
                    }
                }
            }
        }
        $img_url = '/' . $path . $goods_thumb_name;

        return $img_url;
    } catch (think\Exception $e) {

        return $original_img;
    }
}
/**
 * 商品相册缩略图
 */
function get_sub_images($sub_img, $goods_id, $width, $height){
    //判断缩略图是否存在
    $path = "public/upload/goods/thumb/$goods_id/";
    $goods_thumb_name = "goods_sub_thumb_{$sub_img['img_id']}_{$width}_{$height}";

    //这个缩略图 已经生成过这个比例的图片就直接返回了
    if (is_file($path . $goods_thumb_name . '.jpg')) return '/' . $path . $goods_thumb_name . '.jpg';
    if (is_file($path . $goods_thumb_name . '.jpeg')) return '/' . $path . $goods_thumb_name . '.jpeg';
    if (is_file($path . $goods_thumb_name . '.gif')) return '/' . $path . $goods_thumb_name . '.gif';
    if (is_file($path . $goods_thumb_name . '.png')) return '/' . $path . $goods_thumb_name . '.png';

    $ossClient = new \app\common\logic\OssLogic;
    if (($ossUrl = $ossClient->getGoodsAlbumThumbUrl($sub_img['image_url'], $width, $height))) {
        return $ossUrl;
    }

    $original_img = '.' . $sub_img['image_url']; //相对路径
    if (!is_file($original_img)) {
        return '';
    }

    vendor('topthink.think-image.src.Image');
    if(strstr(strtolower($original_img),'.gif'))
    {
        vendor('topthink.think-image.src.image.gif.Encoder');
        vendor('topthink.think-image.src.image.gif.Decoder');
        vendor('topthink.think-image.src.image.gif.Gif');
    }
    $image = \think\Image::open($original_img);

    !is_dir($path) && mkdir($path, 0777, true);
    $goods_thumb_name = $goods_thumb_name . '.' . $image->type();

    // 生成缩略图
    $image->thumb($width, $height, 2)->save($path . $goods_thumb_name, NULL, 100); //按照原图的比例生成一个最大为$width*$height的缩略图并保存
    return '/' . $path . $goods_thumb_name;
}
function money($price,$k=0){
    if(is_numeric($price)){
        $p = explode('.',number_format($price,2,".",""));
        return $p[$k];
    }
}


/**
 * 获取订单状态的 中文描述名称
 * @param type $order_id  订单id
 * @param type $order     订单数组
 * @return string
 */
function orderStatusDesc($order_id = 0, $order = array()){
    if(empty($order))
        $order = M('Order')->where("order_id", $order_id)->find();

    // 货到付款
    if($order['pay_code'] == 'cod')
    {
        if(in_array($order['order_status'],array(0,1)) && $order['shipping_status'] == 0)
            return 'WAITSEND'; //'待发货',
    }
    else // 非货到付款
    {
        if($order['pay_status'] == 0 && $order['order_status'] == 0)
            return 'WAITPAY'; //'待支付',
        if($order['pay_status'] == 1 &&  in_array($order['order_status'],array(0,1)) && $order['shipping_status'] == 0)
            return 'WAITSEND'; //'待发货',
        if($order['pay_status'] == 1 &&  $order['shipping_status'] == 2 && $order['order_status'] == 1)
            return 'PORTIONSEND'; //'部分发货',
    }
    if(($order['shipping_status'] == 1) && ($order['order_status'] == 1))
        return 'WAITRECEIVE'; //'待收货',
    if($order['order_status'] == 2)
        return 'WAITCCOMMENT'; //'待评价',
    if($order['order_status'] == 3)
        return 'CANCEL'; //'已取消',
    if($order['order_status'] == 4)
        return 'FINISH'; //'已完成',
    if($order['order_status'] == 5)
        return 'CANCELLED'; //'已作废',
    return 'OTHER';
}
/**
 * 只保留字符串首尾字符，隐藏中间用*代替（两个字符时只显示第一个）
 * @param string $user_name 姓名
 * @return string 格式化后的姓名
 */
function str_cut($user_name,$is_show){
    if($is_show != 1){
        return $user_name;
    }
    $strlen     = mb_strlen($user_name, 'utf-8');
    $firstStr     = mb_substr($user_name, 0, 1, 'utf-8');
    $lastStr     = mb_substr($user_name, -1, 1, 'utf-8');
    return $strlen == 2 ? $firstStr . str_repeat('*', mb_strlen($user_name, 'utf-8') - 1) : $firstStr . str_repeat("*", $strlen - 2) . $lastStr;
}
/**
 * 获取商品库存
 * @param type $goods_id 商品id
 * @param type $key  库存 key
 */
function getGoodNum($goods_id, $key){
    if(!empty($key))
        return M("SpecGoodsPrice")->where(['goods_id' => $goods_id, 'key' => $key])->getField('store_count');
    else
        return  M("Goods")->where("goods_id", $goods_id)->getField('store_count');
}
/**
 * 计算订单金额
 * @param type $order_goods  购买的商品
 */

function calculate_price($order_goods){

    if (empty($order_goods)){
        return array('status' => -9, 'msg' => '商品列表不能为空', 'result' => '');
    }
    $goods_price = 0;
    $a_num = 0;
    foreach ($order_goods as $key => $val) {
        $is_on_sale = M('goods')->where(['goods_id' => $val['goods_id']])->getField('is_on_sale');
        if ($is_on_sale == 0){
            return array('status' => -10, 'msg' => $val['goods_name'] . "已下架，请重新下单", 'result' => '');
        }
        $val['goods_fee'] = $val['goods_num'] * $val['goods_price'];    // 小计
        $val['store_count'] = getGoodNum($val['goods_id'], $val['spec_key']); // 最多可购买的库存数量
        if ($val['store_count'] <= 0)
            return array('status' => -10, 'msg' => $val['goods_name'] . "库存不足,请重新下单", 'result' => '');

        $goods_price += $val['goods_fee']; // 商品总价
        $a_num += $val['goods_num']; // 购买数量
        $order_goods[$key] = $val;
    }

    //订单总价  应付金额
    $result = array(
        'goods_price' => $goods_price, // 商品总价
        'anum' => $a_num, // 商品总共数量
        'order_goods' => $order_goods
    );
    return array('status' => 1, 'msg' => "计算价钱成功", 'result' => $result); // 返回结果状态
}

/**
 * 根据 order_goods 表扣除商品库存
 * @param type $order_id  订单id
 * @return int $count pv总值
 */
function minus_stock($order_id){
    $orderGoodsArr = M('OrderGoods')->master()->where("order_id", $order_id)->select();
    $count = 0;
    foreach($orderGoodsArr as $key => $val){
        $count += $val['give_integral'];
        // 有选择规格的商品
        if(!empty($val['spec_key'])){   // 先到规格表里面扣除数量 再重新刷新一个 这件商品的总数量
            M('SpecGoodsPrice')->where(['goods_id'=>$val['goods_id'],'key'=>$val['spec_key']])->setDec('store_count',$val['goods_num']);
            refresh_stock($val['goods_id']);
        }else{
            M('Goods')->where("goods_id", $val['goods_id'])->setDec('store_count',$val['goods_num']); // 直接扣除商品总数量
        }
        M('Goods')->where("goods_id", $val['goods_id'])->setInc('sell_count',$val['goods_num']); // 增加商品销售量
    }
    return $count;
}

/**
 * 根据 order_goods 表扣除商品库存
 * @param type $order_id  订单id
 * @return int $count pv总值
 */
function minus_stock2($order_id){
    $orderGoodsArr = M('meal_order_goods')->master()->where("order_id", $order_id)->select();
    $count = 0;
    foreach($orderGoodsArr as $key => $val){
        $count += $val['give_integral'];
        // 有选择规格的商品
        if(!empty($val['spec_key'])){   // 先到规格表里面扣除数量 再重新刷新一个 这件商品的总数量
            M('SpecGoodsPrice')->where(['goods_id'=>$val['goods_id'],'key'=>$val['spec_key']])->setDec('store_count',$val['goods_num']);
            refresh_stock($val['goods_id']);
        }else{
            M('Goods')->where("goods_id", $val['goods_id'])->setDec('store_count',$val['goods_num']); // 直接扣除商品总数量
        }
        M('Goods')->where("goods_id", $val['goods_id'])->setInc('sell_count',$val['goods_num']); // 增加商品销售量
    }
    return $count;
}

/**
 * 订单操作日志
 * 参数示例
 * @param type $order_id  订单id
 * @param type $action_note 操作备注
 * @param type $status_desc 操作状态  提交订单, 付款成功, 取消, 等待收货, 完成
 * @param type $user_id  用户id 默认为管理员
 * @return boolean
 */
function logOrder($order_id,$action_note,$status_desc,$user_id = 0,$admin_id = 0){

    $order = M('order')->master()->where("order_id", $order_id)->find();
    $action_info = array(
        'order_id'        =>$order_id,
        'action_user'     =>$admin_id,
        'order_status'    =>$order['order_status'],
        'action_note'     => $action_note,
        'status_desc'     =>$status_desc, //''
        'log_time'        =>time(),
    );
    return M('order_action')->insert($action_info);
}
/**
 * 获取用户信息
 * @param $user_id_or_name  用户id 邮箱 手机
 * @param int $type  类型 0 user_id查找 1 邮箱查找 2 手机查找
 * @return mixed
 */
function get_user_info($user_id_or_name,$type = 0){
    $map = array();
    if($type == 0)
        $map['user_id'] = $user_id_or_name;
    if($type == 1)
        $map['email'] = $user_id_or_name;
    if($type == 2)
        $map['phone'] = $user_id_or_name;
    $user = M('user')->where($map)->find();
    return $user;
}
/**
 * 检测是否能够发送短信
 * @param unknown $scene
 * @return multitype:number string
 */
function checkEnableSendSms($scene){
    $scenes = C('SEND_SCENE');
    $sceneItem = $scenes[$scene];
    if (!$sceneItem) {
        return array("status" => -1, "msg" => "场景参数'scene'错误!");
    }
    $key = $sceneItem[2];
    $sceneName = $sceneItem[0];
    $config = tpCache('sms');
    $smsEnable = $config[$key];

    if (!$smsEnable) {
        return array("status" => -1, "msg" => "['$sceneName']发送短信被关闭'");
    }
    $size = M('sms_template')->where("send_scene", $scene)->count('tpl_id');
    if (!$size) {
        return array("status" => -1, "msg" => "请先添加['$sceneName']短信模板");
    }
    return array("status"=>1,"msg"=>"可以发送短信");
}
/**
 * 发送短信逻辑
 * @param unknown $scene
 */
function sendSms($scene, $sender, $params){

    $smsLogic = new \app\common\logic\SmsLogic;
    return $smsLogic->sendSms($scene, $sender, $params);
}
/**
 * 根据id获取地区名字
 * @param $regionId id
 */
function getRegionName($regionId){
    $data = M('region')->where(array('id'=>$regionId))->field('name')->find();
    return $data['name'];
}
/*
 * 获取地区列表
 */
function get_region_list(){
    return M('region')->cache(true)->getField('id,name');
}
/*
 * 获取用户地址列表
 */
function get_user_address_list($user_id){
    $lists = M('user_address')->where(array('user_id'=>$user_id))->select();
    return $lists;
}
function getIp(){
    if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }elseif(isset($_SERVER['HTTP_CLIENT_IP'])){
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    }else{
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    $long = sprintf("%u", ip2long($ip));
    $ip   = $long ? [$ip, $long] : ['0.0.0.0', 0];
    return $ip[0];
}
function basic_draw($money){
    $m = trim($money,'-');
    $basic['oundage'] = tpCache('basic.poundage');
    $basic['point_rate'] = tpCache('basic.point_rate');
    $t_m = ($m - $basic['oundage']) / ($basic['point_rate']);
    return number_format($t_m,2,".","");
}
/**
 * 获取某个商品分类的 儿子 孙子  重子重孙 的 id
 * @param type $cat_id
 */
function getCatGrandson ($cat_id)
{
    $GLOBALS['catGrandson'] = array();
    $GLOBALS['category_id_arr'] = array();
    // 先把自己的id 保存起来
    $GLOBALS['catGrandson'][] = $cat_id;
    // 把整张表找出来
    $GLOBALS['category_id_arr'] = M('GoodsCategory')->cache(true,MT_CACHE_TIME)->getField('id,parent_id');
    // 先把所有儿子找出来
    $son_id_arr = M('GoodsCategory')->where("parent_id", $cat_id)->cache(true,MT_CACHE_TIME)->getField('id',true);
    foreach($son_id_arr as $k => $v)
    {
        getCatGrandson2($v);
    }
    return $GLOBALS['catGrandson'];
}
/**
 * 递归调用找到 重子重孙
 * @param type $cat_id
 */
function getCatGrandson2($cat_id)
{
    $GLOBALS['catGrandson'][] = $cat_id;
    foreach($GLOBALS['category_id_arr'] as $k => $v)
    {
        // 找到孙子
        if($v == $cat_id)
        {
            getCatGrandson2($k); // 继续找孙子
        }
    }
}

function cate_name($cat_id){
    return M('GoodsCategory')->where('id',$cat_id)->find();
}


function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true) {
    if(function_exists("mb_substr"))
        $slice = mb_substr($str, $start, $length, $charset);
    elseif(function_exists('iconv_substr')) {
        $slice = iconv_substr($str,$start,$length,$charset);
        if(false === $slice) {
            $slice = '';
        }
    }else{
        $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("",array_slice($match[0], $start, $length));
    }
    return $suffix ? $slice.'...' : $slice;
}


function update_pay_status($order_sn,$trade_no){
    $order  = M('order')->where('order_sn='.$order_sn)->find();
    if (!empty($order)) {
        $data['order_status'] = 1;
        $data['pay_time'] = time();
        $data['transaction_id']= $trade_no;
        if ($data['coupon_id'])   M('coupon')->where(['coupon_id'=>$data['coupon_id']])->update(['use'=>1]);
        M('order')->where('order_sn='.$order_sn)->save($data);
    }
}


//默认昵称
function mobile_name($str){

    $str1=substr($str,0,3);
    $str2=substr($str,3,5);
    $str3=substr($str,-3);
    for($i=0;$i<strlen($str2);$i++){
        $str1.='*';
    }
    $str=$str1.$str3;

    return $str;
}

//生成二维码
function qrCode($url,$user_id){
    vendor('phpqrcode.phpqrcode');
    error_reporting(E_ERROR);
    $qr_code_path = './public/upload/qr_code/';
    if (!file_exists($qr_code_path)) {
        mkdir($qr_code_path);exit();
    }
    $qr_code_file = $qr_code_path.$user_id.'.png';
    $QRcode = new \QRcode();
    $return = $QRcode->png($url,$qr_code_file, QR_ECLEVEL_M,14,2);
    //file_put_contents('a.txt',print_r($return,true),FILE_APPEND);
    return trim($qr_code_file,'.');
}



//修改订单状态
function edit_order($order_id,$transaction_id,$type,$user_id,$is_use,$order_sn){
    if ($type == 2){ //充值订单
        //标识订单
        M('recharge')->where(array('recharge_id' => $order_id))->save(array(
            'status' => 1,
            'pay_time' => time(),
            'transaction_id' => $transaction_id
        ));
        //增加余额
        $amount = M('recharge')->where(array('recharge_id' => $order_id))->getField('amount');
        M('user')->where(array('user_id' => $user_id))->setInc('balance',$amount);
        //增加消费充值记录
        M('expense')->insert(array(
            'user_id' => $user_id,
            'type' => 2, //充值
            'add_time' => time(),
            'amount' => $amount,
            'remark' => '充值-微信支付'
        ));
    }elseif ($type == 3){ //商场订单




        if ((int)$is_use == 0){ //微信支付
            M('shop_order')->where(array('order_id' => $order_id))->save(array(
                'order_status' => 1, //待收货/已支付
                'pay_time' => time(), //支付时间
                'pay_code' => '微信支付', //支付方式
                'transaction_id' => $transaction_id, //第三方流水号
            ));
        }elseif ((int)$is_use == 1){ // 积分+微信
            //扣除积分
            M('user')->where(array('user_id' => $user_id))->save(array('integral' => 0));
            //标识订单状态
            M('shop_order')->where(array('order_id' => $order_id))->save(array(
                'order_status' => 1, //待收货/已支付
                'pay_time' => time(), //支付时间
                'pay_code' => '微信支付', //支付方式
                'transaction_id' => $transaction_id, //第三方流水号
            ));
        }
    }elseif ($type == 4){ //点餐订单
        //标识订单已经支付
        M('meal_order')->where(array('order_id' => $order_id))->save(array(
            'order_status' => 1, //已支付
            'pay_time' => time(),
            'pay_code' => '微信支付',
            'transaction_id' => $transaction_id //第三方流水号
        ));
    }else{ //预约订单
        if ((int)$is_use == 0){//直接使用微信支付

            $data = M('order')->where(array('order_sn' => $order_sn))->field(true)->find();
            if ($data['coupon_id'])   M('coupon')->where(['coupon_id'=>$data['coupon_id']])->update(['use'=>1]);
            //标识订单状态
            M('order')->where(array('order_sn' => $order_sn))->save(array(
                'order_status' => 1,
                'pay_time' => time(),
                'pay_code' => '微信支付',
                'transaction_id' => $transaction_id,
            ));
            $amount = M('order')->where(array('order_id' => $order_id))->getField('goods_price');
            //增加消费记录
            M('expense')->insert(array(
                'user_id' => $user_id,
                'type' => 1, //消费
                'add_time' => time(),
                'amount' => $amount,
                'remark' => '预约订单-微信支付'
            ));
        }
        if ((int)$is_use == 1){ //余额+微信支付
            $data = M('order')->where(array('order_sn' => $order_sn))->field(true)->find();
            if ($data['coupon_id'])   M('coupon')->where(['coupon_id'=>$data['coupon_id']])->update(['use'=>1]);
            //标识订单状态
            M('order')->where(array('order_sn' => $order_sn))->save(array(
                'order_status' => 1,
                'pay_time' => time(),
                'pay_code' => '余额+微信支付',
                'transaction_id' => $transaction_id
            ));
            //扣除余额
            M('user')->where(array('user_id' => $user_id))->save(array('balance' => 0));
            //增加消费记录
            //增加消费充值记录
            $amount = M('order')->where(array('order_id' => $order_id))->getField('goods_price');
            M('expense')->insert(array(
                'user_id' => $user_id,
                'type' => 1, //消费
                'add_time' => time(),
                'amount' => $amount,
                'remark' => '预约订单-余额+微信支'
            ));
        }


        file_put_contents('notice.txt',json_encode($data,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
        //发送短信
        /**
         * 发送电话 $data['phone']
         * 预约时间 $data['subscribe_time']
         * 球位位置 $data['goods_name']
         */
        $result = (new \app\common\logic\SmsLogic)->notice(
            $data['phone'],
            date('Y年m月d日',$data['subscribe_time']),
            mb_substr($data['goods_name'],2,1,'utf-8'),
            date('H:i',$data['subscribe_time'])
            );
        file_put_contents('notice.txt',json_encode($result,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);



    }

}


function urlGet($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_REFERER, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $result = curl_exec($ch);
    curl_close($ch);
    $result = json_decode($result, true);
    return $result;
}

function urlPost($url, $post_data){
    $post_data = json_encode($post_data);
    $header = array("Content-Type:multipart/x-www-form-urlencoded", "token:test", "client:h5");
    $ch = curl_init();    // 启动一个CURL会话
    curl_setopt($ch, CURLOPT_URL, $url);     // 要访问的地址
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  // 对认证证书来源的检查   // https请求 不验证证书和hosts
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
//curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
//curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
    curl_setopt($ch, CURLOPT_POST, true); // 发送一个常规的Post请求
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);     // Post提交的数据包
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);     // 设置超时限制防止死循环
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
//curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);     // 获取的信息以文件流的形式返回
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header); //模拟的header头
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

